package com.hongxinguoji.manager.admin.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hongxinguoji.manager.admin.pojo.HxAuthFunction;
import com.hongxinguoji.manager.admin.pojo.HxUser;
import com.hongxinguoji.manager.admin.service.IUserService;
import com.hongxinguoji.manager.common.util.EasyUIDataGridResult;
import com.hongxinguoji.manager.common.util.HXResult;
import com.hongxinguoji.manager.common.util.IDUtils;
import com.hongxinguoji.manager.common.util.MD5Utils;

@Service
@RequestMapping("/admin")
public class UserController {

	@Autowired
	private IUserService userService;

	@RequestMapping("/userlist")
	@ResponseBody
	public EasyUIDataGridResult getUserList(Integer page, Integer rows) {
		EasyUIDataGridResult result = new EasyUIDataGridResult();
		// 分页处理
		PageHelper.startPage(page, rows);
		List<HxUser> list = userService.getUserList();

		PageInfo<HxUser> pageInfo = new PageInfo<>(list);
		result.setTotal(pageInfo.getTotal());
		result.setRows(list);

		return result;

	}

	@RequestMapping("/adduser")
	@ResponseBody
	public HXResult addUser(HxUser user, String[] roleIds) {
		try {
			// 补全属性
			String id = IDUtils.getNumStringId();
			user.setId(id);
			userService.addUser(user, roleIds);
			return HXResult.ok("添加用户成功！");

		} catch (Exception e) {
			e.printStackTrace();
			return HXResult.build(500, "添加用户失败！");
		}
	}

	@RequestMapping("/userlock")
	@ResponseBody
	public HXResult lockUser(String ids) {

		try {
			String[] idStrings = ids.split(",");
			for (String id : idStrings) {
				userService.lockUserById(id);
			}
			return HXResult.ok("锁定用户成功！");

		} catch (Exception e) {
			return HXResult.ok("锁定用户失败！");
		}

	}

	@RequestMapping("/userunlock")
	@ResponseBody
	public HXResult unlockUser(String ids) {
		try {
			String[] idStrings = ids.split(",");
			for (String id : idStrings) {
				userService.unlockUserById(id);
			}
			return HXResult.ok("解锁用户成功！");

		} catch (Exception e) {
			return HXResult.ok("解锁用户失败！");
		}
	}

	/**
	 * 修改用户
	 * 
	 * @param user
	 * @param roleIds
	 * @return
	 */
	@RequestMapping("/edituser")
	@ResponseBody
	public HXResult updateUser(HxUser user, String[] roleIds) {

		userService.updateUser(user, roleIds);
		return HXResult.ok();

	}

	@RequestMapping("/userdelete")
	@ResponseBody
	public HXResult deleteUser(String ids) {

		try {
			String[] idStrings = ids.split(",");
			for (String id : idStrings) {
				userService.deleteUserById(id);
			}
			return HXResult.ok("删除用户成功！");
		} catch (Exception e) {
			return HXResult.build(200, "删除用户失败！");
		}
	}

	/**
	 * 用户登录
	 */
	@RequestMapping("/login")
	public String login(HttpSession session, String checkcode, HxUser model) {
		// 获取生成的验证码
		String key = (String) session.getAttribute("key");
		// 判断用户输入的验证码是否正确
		if (StringUtils.isNotBlank(checkcode) && checkcode.equals(key)) {
			// 验证码正确
			// 获得当前用户对象
			Subject subject = SecurityUtils.getSubject();
			String password = model.getPassword();
			password = MD5Utils.md5(password);
			// 构造一个用户名密码令牌
			AuthenticationToken token = new UsernamePasswordToken(model.getUsername(), password);
			try {
				subject.login(token);
			} catch (UnknownAccountException e) {
				e.printStackTrace();
				return "redirect:/index.jsp";
			} catch (Exception e) {
				e.printStackTrace();
				return "redirect:/index.jsp";
			}
			// 获取认证信息对象中存储的User对象
			HxUser user = (HxUser) subject.getPrincipal();
			// 用户登录登录成功
			session.setAttribute("loginUser", user);
			return "redirect:/home.jsp";
		} else {
			return "redirect:/index.jsp";
		}
	}

	/**
	 * 获取用户树形菜单
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping("/getUserMenuList")
	@ResponseBody
	public List<HxAuthFunction> getUserMenuList(HttpSession session) {
		HxUser user = (HxUser) session.getAttribute("loginUser");
		List<HxAuthFunction> list = userService.getUserMenuList(user);
		return list;
	}

	/**
	 * 用户退出登录
	 * 
	 * @return
	 */
	@RequestMapping("/logout")
	public String logout() {
		Subject subject = SecurityUtils.getSubject();
		if (subject.isAuthenticated()) {
			// session 会销毁，在SessionListener监听session销毁，清理权限缓存
			subject.logout();
		}
		return "redirect:/index.jsp";
	}

	/**
	 * 修改用户密码
	 * 
	 * @return
	 */
	@RequestMapping("/changePwd")
	@ResponseBody
	public HXResult changePwd(HttpSession session, String password) {
		HxUser user = (HxUser) session.getAttribute("loginUser");

		try {
			userService.changePwd(user.getId(), password);
			return HXResult.ok("1");
		} catch (Exception e) {
			e.printStackTrace();
			return HXResult.ok("2");
		}

	}
}
